package com.ldy.core.util;

import java.util.HashMap;
import java.util.Map;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;

/**
 * jwt
 */
public class JwtUtil {
	
	private static final String USERID = "userId";
	
	private static final byte[] KEY = "ldytest123456".getBytes();;


	/**
	 * 生成token
	 * @param username
	 * @return
	 * @throws Exception
	 */
	public static String generateToken(String username) throws Exception {
			Map<String, Object> payload = new HashMap<String, Object>();
			payload.put(USERID, username);
			return JWTUtil.createToken(payload, KEY);
	}

	/**
	 * 验证 token
	 * @param token
	 * @return
	 * @throws Exception
	 */
	public static String verifyToken(String token) throws Exception {
		if (JWTUtil.verify(token, KEY)) {
			JWT jwt = JWTUtil.parseToken(token);
			return (String)jwt.getPayload(USERID);
		}
		return null;
	}

	public static void main(String[] args) throws Exception {
//		JwtUtil jwtUtil = new JwtUtil();
//		jwtUtil.privateKeyPath = "/Users/lindeyi/private_key.pem";
//		jwtUtil.publicKeyPath = "/Users/lindeyi/public_key.pem";
//		String jwt = jwtUtil.generateToken("user123");
//		System.out.println("Generated Token: " + jwt);
//
//		Claims claims = jwtUtil.verifyToken(jwt);
//		if (claims != null) {
//			System.out.println("Token verified, username: " + claims.getSubject());
//		}
		byte[] key = "ldytest123456".getBytes();
		String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJ6aGFuZ3NhbjIyMiJ9.XOBNiMqmybANFUKT3SN42TUBGmJd2T2fef35oalb5VU";
		System.out.println(token);
		if (JWTUtil.verify(token, key)) {
			JWT jwt = JWTUtil.parseToken(token);
			System.out.println(jwt.getPayload("userId"));
		}
	}
}
